package com.haizhi.crm.common.util;

import org.apache.shiro.crypto.hash.Sha1Hash;
import org.apache.shiro.crypto.hash.SimpleHash;

/**
 * Created by gikieng on 18/2/2.
 */


public class PasswordEncrypt {
    public static final String ENCRYPT_SEPERATOR = "$";
    public static final Integer DEFAULT_SALT_LEN = 8;
    public static final Integer DEFAULT_PWD_LEN = 6;
    static final Integer DEFAULT_HASH_ITERATIONS = 1000;
    static final String DEFAULT_PWD = "123456";
    static final String SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    static final String HASH_METHOD = "Sha1Hash";

    public static String randomSalt() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < DEFAULT_SALT_LEN; i++) {
            Long index = Math.round(Math.random() * SALT_CHARS.length());
            sb.append(SALT_CHARS.charAt(index.intValue()));
        }
        return sb.toString();
    }

    public static String buildEncryptPassword(String password, String salt, int hashIterations) {
        SimpleHash builder = new Sha1Hash(password, salt, hashIterations);
        StringBuilder sb = new StringBuilder();
        String pwd = builder.getAlgorithmName() + ENCRYPT_SEPERATOR
                + DEFAULT_HASH_ITERATIONS.toString() + ENCRYPT_SEPERATOR
                + salt + ENCRYPT_SEPERATOR + builder.toString();
        return pwd;
    }

    public static String buildEncryptPassword(String password, String salt) {
        return buildEncryptPassword(password, salt, DEFAULT_HASH_ITERATIONS);
    }

    public static String buildEncryptPassword(String password) {
        String salt = randomSalt();
        return buildEncryptPassword(password, salt);
    }

    public static String buildEncryptPassword() {
        return buildEncryptPassword(DEFAULT_PWD);
    }

    public static PasswordInfo extractEncryptPassword(String password) {
        return new PasswordInfo(password);
    }

    public static Boolean matchPassword(String originPassword, String encryptPassword) {
        PasswordInfo passwordInfo = extractEncryptPassword(encryptPassword);
        return encryptPassword.equals(buildEncryptPassword(originPassword, passwordInfo.salt(), passwordInfo.hashIterations()));
    }
}